//
//  MTCPumpModifPriceViewController.m
//  ERP
//
//  Created by goldeney on 15/6/17.
//  Copyright (c) 2015年 ShangHai Goldeneye Techonology Co.,Ltd. All rights reserved.
//

#import "MTCPumpModifPriceViewController.h"

#import "GEPickerTextField.h"
#import "NSDictionary+DataFormat.h"
#import "ServiceConnect.h"
#import "CustomIOSAlertView.h"
#import "NSKeyedArchiverUserLogin.h"

#import "GEInputTableViewCell.h"
#import "MTCPumpModifPriceViewCell.h"

#import "MLPAutoCompleteTextField.h"
#import "AFViewShaker.h"
#import "DEMOCustomAutoCompleteObject.h"

@interface MTCPumpModifPriceViewController()<UITextFieldDelegate,MLPAutoCompleteTextFieldDelegate,
MLPAutoCompleteTextFieldDataSource>

@property (strong, nonatomic) NSMutableArray *resultData;
@property (strong, nonatomic) NSMutableArray *deleteData;

@property (strong, nonatomic) NSMutableArray *pumpingClassArray;
@property (strong, nonatomic) NSMutableArray *pumpingModelArray;

@property (strong, nonatomic) NSMutableDictionary *pumpingClassSelectedObject;
@property (strong, nonatomic) NSMutableDictionary *pumpingModelSelectedObject;
@property (assign, nonatomic) NSInteger getNetworkDataState;

@property (strong, nonatomic) NSString *concreteID;
@property (strong, nonatomic) NSString *takeTime;
@property (strong, nonatomic) NSArray *historyTime;

@end

@implementation MTCPumpModifPriceViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self setTitle: @"泵送价格新增修改"];
        
        // Custom initialization
        UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:@"提交" style:UIBarButtonItemStyleDone target:self
                                                                      action:@selector(submitConcretePriceSelector:)];
        self.navigationItem.rightBarButtonItem = leftButton;
    }
    return self;
}

- (id)initWithConcreteID:(NSString*)concreteID takeTime:(NSString*)time historyTime:(NSArray*)historyTime
{
    self = [super init];
    if (self) {
        self.concreteID = concreteID;
        self.takeTime = time;
        self.historyTime = historyTime;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.pumpingClassArray = [NSMutableArray array];
    self.pumpingModelArray = [NSMutableArray array];
    self.resultData = [NSMutableArray array];
    self.deleteData = [NSMutableArray array];
    [self getBSZLListInfo];//获取泵送种类列表
    [self getBSXHListInfo];//获取泵送类型列表
    
    [self.pumpClassTextField registerAutoCompleteCellClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"];
    self.pumpClassTextField.autoCompleteTableCellBackgroundColor = [UIColor whiteColor];
    self.pumpClassTextField.autoCompleteRowHeight = 30;
    self.pumpClassTextField.maximumNumberOfAutoCompleteRows = 4;
    
    [self.pumpModelTextField registerAutoCompleteCellClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"];
    self.pumpModelTextField.autoCompleteTableCellBackgroundColor = [UIColor whiteColor];
    self.pumpModelTextField.autoCompleteRowHeight = 30;
    self.pumpModelTextField.maximumNumberOfAutoCompleteRows = 4;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark
#pragma mark - 网络获取数据

//获取泵送种类列表
- (void)getBSZLListInfo
{
    //增加 6-泵送种类
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeGroup];
    [content setModuleType:@"HTGL_JCXX_LIST"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    [content addParameterKey:@"Type" value:@6];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        NSArray *firstArray = nil;
        if(result.resultArray && result.resultArray.count>0)
            firstArray = [result.resultArray firstObject];
        
        if(firstArray && firstArray.count>0){
            [self.pumpingClassArray removeAllObjects];
            [self.pumpingClassArray addObjectsFromArray:firstArray];
        }
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
    }];
}

//获取泵送型号列表
- (void)getBSXHListInfo
{
    //增加7-泵送型号
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeGroup];
    [content setModuleType:@"HTGL_JCXX_LIST"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    [content addParameterKey:@"Type" value:@7];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        NSArray *firstArray = nil;
        if(result.resultArray && result.resultArray.count>0)
            firstArray = [result.resultArray firstObject];
        
        if(firstArray && firstArray.count>0){
            [self.pumpingModelArray removeAllObjects];
            [self.pumpingModelArray addObjectsFromArray:firstArray];
        }
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
    }];
}

#pragma mark
#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section == 0) {
        return 2;
    } else if(section == 1) {
        if (self.getNetworkDataState < 0) return 1;
        return self.resultData.count + 1;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        GEInputTableViewCell *cell = [self.tableView getCellViewInRow:indexPath.row inSection:indexPath.section];
        if (cell != nil) return cell;
        
        if(indexPath.row == 0){
            NSString *CellIdentifier = [NSString stringWithFormat:@"GEInputTableViewCell%ld%ld",indexPath.section,indexPath.row];
            cell = [[GEInputTableViewCell alloc] initWithDateReuseIdentifier:CellIdentifier];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.titleName = @"生效时间";
            cell.placeholder = @"请选择生效时间";
            cell.isChangeWidth = YES;
            [self.tableView setCellView:cell inRow:indexPath.row inSection:indexPath.section];
            [cell addDoneTarget:self action:@selector(dataChangeSelector:)];
            
            UITextField *textField = [self.tableView getCellSaveClass:[UITextField class]
                                                           pathForRow:indexPath.row inSection:indexPath.section];
            if (self.takeTime) textField.text = self.takeTime;
            [self getTimeNodeNetworkDate:textField.text];
            
        } else if(indexPath.row == 1){
            NSString *CellIdentifier = [NSString stringWithFormat:@"GEInputTableViewCell%ld%ld",indexPath.section,indexPath.row];
            cell = [[GEInputTableViewCell alloc] initWithSelectReuseIdentifier:CellIdentifier request:nil];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.titleName = @"历史时间";
            cell.placeholder = @"历史数据将添加到列表中";
            cell.isChangeWidth = YES;
            cell.isMark = NO;
            [self.tableView setCellView:cell inRow:indexPath.row inSection:indexPath.section];
            [cell addDoneTarget:self action:@selector(dataBGChangeSelector:)];
            
            if (self.historyTime) {
                NSDictionary *Time = [NSDictionary dictionaryWithObject:@"%@" forKey:@"Time"];
                [cell setPickerTextFieldComponents:self.historyTime keyValue:@[Time]];
            }
        }
        return cell;
        
    } else if (indexPath.section == 1) {
        if (self.getNetworkDataState < 0) { //获取数据中
            NSString *CellIdentifier = [NSString stringWithFormat:@"GetNetworkDataState%ld%ld",indexPath.section,indexPath.row];
            UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            
            if(self.getNetworkDataState == -1) {//加载进度条
                UIActivityIndicatorView *act=[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
                act.center = CGPointMake(SuperWidth/2, 22.0f);
                act.activityIndicatorViewStyle=UIActivityIndicatorViewStyleGray;
                [act startAnimating];
                [cell.contentView addSubview:act];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                
            } else if(self.getNetworkDataState == -2){//显示失败提示
                UILabel* label = [[UILabel alloc] initWithFrame:cell.contentView.frame];
                label.text = @"加载失败，点击重试";
                label.center = CGPointMake(SuperWidth/2, 22.0f);
                label.font = [UIFont fontWithName:@"Arial" size:14];
                label.textColor = [UIColor darkGrayColor];
                label.textAlignment = NSTextAlignmentCenter;
                [cell.contentView addSubview:label];
                cell.selectionStyle = UITableViewCellSelectionStyleDefault;
                
            } else if(self.getNetworkDataState == -3){//显示失败提示
                UILabel* label = [[UILabel alloc] initWithFrame:cell.contentView.frame];
                label.text = @"网络异常，点击重试";
                label.font = [UIFont fontWithName:@"Arial" size:14];
                label.textColor = [UIColor darkGrayColor];
                label.textAlignment = NSTextAlignmentCenter;
                [cell.contentView addSubview:label];
                cell.selectionStyle = UITableViewCellSelectionStyleDefault;
            }
            return cell;
            
        } else if (indexPath.row < self.resultData.count) {
            NSString *CellIdentifier = [NSString stringWithFormat:@"MTCPumpModifPriceViewCell"];
            MTCPumpModifPriceViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if (cell == nil){
                cell = [[MTCPumpModifPriceViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
                cell.accessoryType = UITableViewCellAccessoryNone;
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            
            NSDictionary *valueDic = [self.resultData objectAtIndex:indexPath.row];
            cell.JGLabel.text = [NSString stringWithFormat:@"%@元/方",[valueDic objectFormatStringForKey:@"价格"]];
            
            NSString *pumpValueBSZL = [valueDic objectFormatStringForKey:@"泵送种类"];
            NSString *pumpValueBSXH = [valueDic objectFormatStringForKey:@"泵送型号"];
            cell.BSSBLabel.text = [NSString stringWithFormat:@"%@%@",pumpValueBSZL,pumpValueBSXH];
            
            NSString *BZ = [valueDic objectFormatStringForKey:@"备注"];
            BZ = BZ && BZ.length>0 ? BZ : @"无";
            cell.BZLabel.text = BZ;
            
            cell.deleteButton.tag = indexPath.row;
            [cell.deleteButton addTarget:self action:@selector(deletSelector:) forControlEvents:UIControlEventTouchUpInside];
            
            //添加分割线
            UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, cell.frame.size.height - 0.5, SuperWidth, 0.5)];
            lineView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.1];
            [cell.contentView addSubview:lineView];
            return cell;
            
        } else {
            static NSString *TableSampleIdentifier = @"TableSampleIdentifier";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:TableSampleIdentifier];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TableSampleIdentifier];
                
                UIImage *image = [UIImage imageNamed:@"button_bg_add"];
                UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(SuperWidth/2-image.size.width/2, cell.frame.size.height/2-image.size.height/2, image.size.width, image.size.height)];
                [imageView setImage:image];
                [cell.contentView addSubview:imageView];
            }
            return cell;
        }
    }
    
    return nil;
}

#pragma mark
#pragma mark - UITableViewDelegate

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 35)];
    view.backgroundColor = [UIColor colorWithWhite:0.985 alpha:1];
    
    UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 25, 25)];
    image.image = [UIImage imageNamed:@"oa"];
    [view addSubview:image];
    
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(35, 0, SuperWidth - 40, 35)];
    lable.textColor = [UIColor grayColor];
    lable.font = [UIFont systemFontOfSize:17];
    [view addSubview:lable];
    
    if (section == 0) {
        lable.text = @"选择生效时间";
    } else if (section == 1){
        UITextField *textField1 = [self.tableView getCellSaveClass:[UITextField class] pathForRow:0 inSection:0];
        UITextField *textField2 = [self.tableView getCellSaveClass:[UITextField class] pathForRow:1 inSection:0];
        if (textField2 && textField2.text.length >0) {
            lable.text = [NSString stringWithFormat:@"%@ (含历史时间泵送价格)", textField2.text];
        } else if (textField1 && textField1.text.length >0) {
            lable.text = textField1.text;
        } else {
            lable.text = @"无节点数据";
        }
    }
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 34, SuperWidth, 1)];
    lineView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [view addSubview:lineView];
    
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 35;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 20;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    //键盘事件处理
    if(indexPath.section == 0) {
        UITextField *textField = [self.tableView getCellSaveClass:[UITextField class] pathForRow:indexPath.row inSection:indexPath.section];
        if (textField) [textField becomeFirstResponder];
    }
    
    if (indexPath.section == 1 && self.getNetworkDataState < -1){ //获取数据
        UITextField *textField1 = [self.tableView getCellSaveClass:[UITextField class] pathForRow:0 inSection:0];
        UITextField *textField2 = [self.tableView getCellSaveClass:[UITextField class] pathForRow:1 inSection:0];
        if (textField2.text.length > 0) [self getChangeTimeNodeNetworkDate:textField2.text];
        else [self getTimeNodeNetworkDate:textField1.text];
        
    } else if (indexPath.section == 1 && indexPath.row < self.resultData.count) {
        NSDictionary *mDictionary = [self.resultData objectAtIndex:indexPath.row];
        self.jgField.text = [mDictionary objectFormatStringForKey:@"价格"];
        self.bzField.text = [mDictionary objectFormatStringForKey:@"备注"];
        self.pumpClassTextField.text = [mDictionary objectFormatStringForKey:@"泵送种类"];
        self.pumpModelTextField.text = [mDictionary objectFormatStringForKey:@"泵送型号"];
        
        self.pumpingClassSelectedObject = [NSMutableDictionary dictionary];
        [self.pumpingClassSelectedObject setObject:[mDictionary objectFormatStringForKey:@"PumpType"] forKey:@"Status"];
        
        self.pumpingModelSelectedObject = [NSMutableDictionary dictionary];
        [self.pumpingModelSelectedObject setObject:[mDictionary objectFormatStringForKey:@"PumpNorms"] forKey:@"Status"];
        
        //显示对话框
        CustomIOSAlertView *alertView = [[CustomIOSAlertView alloc] init];
        [alertView setContainerView:self.populeView];
        [alertView setButtonTitles:[NSMutableArray arrayWithObjects:@"取消", @"修改", nil]];
        alertView.tag = 1;
        alertView.object = mDictionary;
        [alertView setOnButtonTouchUpInside:^(CustomIOSAlertView *alertView, int buttonIndex) {
            NSLog(@"Block: Button at position %d is clicked on alertView %d.", buttonIndex, (int)[alertView tag]);
            [self viewFinshHandle:alertView index:buttonIndex];
        }];
        [alertView setUseMotionEffects:true];
        [alertView show];
        
    } else if(indexPath.section == 1){
        //显示对话框
        CustomIOSAlertView *alertView = [[CustomIOSAlertView alloc] init];
        [alertView setContainerView:self.populeView];
        [alertView setButtonTitles:[NSMutableArray arrayWithObjects:@"取消", @"新增", nil]];
        alertView.tag = 2;
        [alertView setOnButtonTouchUpInside:^(CustomIOSAlertView *alertView, int buttonIndex) {
            NSLog(@"Block: Button at position %d is clicked on alertView %d.", buttonIndex, (int)[alertView tag]);
            [self viewFinshHandle:alertView index:buttonIndex];
        }];
        [alertView setUseMotionEffects:true];
        [alertView show];
    }
    
}

#pragma mark Data Handle

- (void)viewFinshHandle:(CustomIOSAlertView*)alertView index:(NSInteger)buttonIndex
{
    if (buttonIndex == 1 && (self.pumpClassTextField.text.length <=0 || !self.pumpingClassSelectedObject)) {
        AFViewShaker * viewShaker = [[AFViewShaker alloc] initWithView:self.pumpClassTextField];
        [viewShaker shake];
        return;
    } else if (buttonIndex == 1 && (self.pumpModelTextField.text.length <=0 || !self.pumpModelTextField)) {
        AFViewShaker * viewShaker = [[AFViewShaker alloc] initWithView:self.pumpModelTextField];
        [viewShaker shake];
        return;
    } else if (buttonIndex == 1 && self.jgField.text.length <=0) {
        AFViewShaker * viewShaker = [[AFViewShaker alloc] initWithView:self.jgField];
        [viewShaker shake];
        return;
    } else if (buttonIndex == 1) {
        if(alertView.tag == 2)[self addDataToTableView];
        if(alertView.tag == 1)[self modifDataToTableView:alertView.object];
    }
    [alertView close];
    [self clearPopuleViewData];
}

//判断有无重复节点(整体)
- (BOOL)concreteStrengthIsExist
{
    for (NSDictionary *dictionary in self.resultData) {
        NSNumber *numberClass = [dictionary objectFormatIntegerNumberForKey:@"PumpType"];
        NSNumber *numberModel = [dictionary objectFormatIntegerNumberForKey:@"PumpNorms"];
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"PumpType == %@ and PumpNorms == %@", numberClass, numberModel];
        NSArray *filteredArray = [self.resultData filteredArrayUsingPredicate:predicate];
        if (filteredArray.count > 1) return NO;
    }
    return YES;
}

//判断有无重复节点（单个）
- (BOOL)concreteStrengthIsExist:(NSDictionary*)dictionary
{
    NSNumber *numberClass = [dictionary objectFormatIntegerNumberForKey:@"PumpType"];
    NSNumber *numberModel = [dictionary objectFormatIntegerNumberForKey:@"PumpNorms"];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"PumpType == %@ and PumpNorms == %@", numberClass, numberModel];
    NSArray *filteredArray = [self.resultData filteredArrayUsingPredicate:predicate];
    if (filteredArray.count > 1) return NO;
    else return YES;
}

- (void)clearPopuleViewData
{
    self.pumpClassTextField.text = @"";
    self.pumpModelTextField.text = @"";
    self.jgField.text = @"";
    self.bzField.text = @"";
}

//添加节点
- (void)addDataToTableView
{
    NSMutableDictionary *mDictionary = [NSMutableDictionary dictionary];
    [mDictionary setObject:[NSNumber numberWithInteger:0] forKey:@"ID"];
    [mDictionary setObject:[self.pumpingClassSelectedObject objectFormatIntegerNumberForKey:@"Status"] forKey:@"PumpType"];
    [mDictionary setObject:[self.pumpingModelSelectedObject objectFormatIntegerNumberForKey:@"Status"] forKey:@"PumpNorms"];
    [mDictionary setObject:self.pumpClassTextField.text forKey:@"泵送种类"];
    [mDictionary setObject:self.pumpModelTextField.text forKey:@"泵送型号"];
    [mDictionary setObject:self.jgField.text forKey:@"价格"];
    [mDictionary setObject:self.bzField.text forKey:@"备注"];
    [mDictionary setObject:@"xz" forKey:@"Mark"];
    [self.resultData addObject:mDictionary];
    
    NSIndexSet *indexSet = [[NSIndexSet alloc]initWithIndex:1];
    [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
}

//修改节点
- (void)modifDataToTableView:(NSDictionary*)dictionary
{
    NSMutableDictionary *mDictionary = [NSMutableDictionary dictionaryWithDictionary:dictionary];
    [mDictionary setObject:[self.pumpingClassSelectedObject objectFormatIntegerNumberForKey:@"Status"] forKey:@"PumpType"];
    [mDictionary setObject:[self.pumpingModelSelectedObject objectFormatIntegerNumberForKey:@"Status"] forKey:@"PumpNorms"];
    [mDictionary setObject:self.pumpClassTextField.text forKey:@"泵送种类"];
    [mDictionary setObject:self.pumpModelTextField.text forKey:@"泵送型号"];
    [mDictionary setObject:self.jgField.text forKey:@"价格"];
    [mDictionary setObject:self.bzField.text forKey:@"备注"];
    
    NSInteger index = [self.resultData indexOfObject:dictionary];
    [self.resultData removeObject:dictionary];
    [self.resultData insertObject:mDictionary atIndex:index];
    
    NSIndexSet *indexSet = [[NSIndexSet alloc]initWithIndex:1];
    [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
}

#pragma mark Button Event

- (void)deletSelector:(id)sender
{
    UIButton *button = sender;
    NSDictionary *dictionary = [self.resultData objectAtIndex:button.tag];
    
    if ([dictionary objectFormatIntegerForKey:@"ID"] > 0)
        [self.deleteData addObject:dictionary];
    [self.resultData removeObjectAtIndex:button.tag];
    
    NSIndexSet *indexSet = [[NSIndexSet alloc]initWithIndex:1];
    [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
}

- (void)submitConcretePriceSelector:(id)sender
{
    if (self.resultData.count <= 0) {
        [self showAlertView:@"至少添加一条泵送价格信息，请添加泵送价格信息"];
        return;
    } else if(![self concreteStrengthIsExist]){
        [self showAlertView:@"存在重复泵送价格信息，请删除或者更改"];
        return;
    }
    
    //提示相关消息
    NSString *message = nil;
    UITextField *textField1 = [self.tableView getCellSaveClass:[UITextField class] pathForRow:0 inSection:0];
    UITextField *textField2 = [self.tableView getCellSaveClass:[UITextField class] pathForRow:1 inSection:0];
    if (textField2 && textField2.text.length >0) {
        message = [NSString stringWithFormat:@"本次提交包含历史历史生效时间泵送价格信息，提交后生效时间为%@，请仔细核对后点击提交", textField1.text];
    } else if (textField1 && textField1.text.length >0) {
        message = [NSString stringWithFormat:@"本次提交后生效时间为%@，请仔细核对后点击提交", textField1.text];
    } else {
        [self showAlertView:@"未找到生效时间，无法提交变更"];
        return;
    }
    
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提交说明" message:message delegate:self cancelButtonTitle:@"提交" otherButtonTitles:@"取消", nil];
    alert.alertViewStyle=UIAlertViewStyleDefault;
    [alert show];
}

- (void)dataChangeSelector:(id)sender
{
    //获取数据
    UITextField *textField = [self.tableView getCellSaveClass:[UITextField class] pathForRow:0 inSection:0];
    [self getTimeNodeNetworkDate:textField.text];
}

- (void)dataBGChangeSelector:(id)sender
{
    UITextField *textField = [self.tableView getCellSaveClass:[UITextField class] pathForRow:1 inSection:0];
    [self getChangeTimeNodeNetworkDate:textField.text];
}


#pragma mark 网络提交

//生效时间数据获取
- (void)getTimeNodeNetworkDate:(NSString*)date
{
    //删除所有数据
    self.getNetworkDataState = -1;
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"Mark == %@", @"sx"];
    
    NSArray *filteredArray = [self.resultData filteredArrayUsingPredicate:predicate];
    [self.resultData removeObjectsInArray:filteredArray];
    
    NSArray *deleteArray = [self.deleteData filteredArrayUsingPredicate:predicate];
    [self.deleteData removeObjectsInArray:deleteArray];
    
    NSIndexSet *indexSet = [[NSIndexSet alloc]initWithIndex:1];
    [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
    
    //网络获取数据
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeGroup];
    [content setModuleType:@"HTGL_BSDJ_LIST"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    [content addParameterKey:@"合同ID" value:self.concreteID];
    [content addParameterKey:@"生效时间" value:date];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        //添加数据，刷新页面
        NSArray *firstArray = nil;
        if(result.resultArray && result.resultArray.count>0)
            firstArray = [result.resultArray firstObject];
        
        for(NSDictionary *dictionary in firstArray){
            NSMutableDictionary *newDictionary = [NSMutableDictionary dictionaryWithDictionary:dictionary];
            [newDictionary setObject:@"sx" forKey:@"Mark"];
            [self.resultData addObject:newDictionary];
        }
        
        self.getNetworkDataState = 0;
        NSIndexSet *indexSet = [[NSIndexSet alloc]initWithIndex:1];
        [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        self.getNetworkDataState = -2;
        NSIndexSet *indexSet = [[NSIndexSet alloc]initWithIndex:1];
        [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        self.getNetworkDataState = -3;
        NSIndexSet *indexSet = [[NSIndexSet alloc]initWithIndex:1];
        [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
    }];
}

//变更时间数据获取
- (void)getChangeTimeNodeNetworkDate:(NSString*)date
{
    //删除变更数据
    self.getNetworkDataState = -1;
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"Mark == %@", @"bg"];
    
    NSArray *filteredArray = [self.resultData filteredArrayUsingPredicate:predicate];
    [self.resultData removeObjectsInArray:filteredArray];
    
    NSArray *deleteArray = [self.deleteData filteredArrayUsingPredicate:predicate];
    [self.deleteData removeObjectsInArray:deleteArray];
    
    NSIndexSet *indexSet = [[NSIndexSet alloc]initWithIndex:1];
    [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
    
    //网络获取数据
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeGroup];
    [content setModuleType:@"HTGL_BSDJ_LIST"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    [content addParameterKey:@"合同ID" value:self.concreteID];
    [content addParameterKey:@"生效时间" value:date];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        //添加数据，刷新页面
        NSArray *firstArray = nil;
        if(result.resultArray && result.resultArray.count>0)
            firstArray = [result.resultArray firstObject];
        
        for(NSDictionary *dictionary in firstArray){
            NSMutableDictionary *newDictionary = [NSMutableDictionary dictionaryWithDictionary:dictionary];
            [newDictionary setObject:@"bg" forKey:@"Mark"];
            [newDictionary setObject:@0 forKey:@"ID"];
            [self.resultData addObject:newDictionary];
        }
        
        self.getNetworkDataState = 0;
        NSIndexSet *indexSet = [[NSIndexSet alloc]initWithIndex:1];
        [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        self.getNetworkDataState = -2;
        NSIndexSet *indexSet = [[NSIndexSet alloc]initWithIndex:1];
        [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        self.getNetworkDataState = -3;
        NSIndexSet *indexSet = [[NSIndexSet alloc]initWithIndex:1];
        [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
    }];
}

- (void)submitNetworkData
{
    //获取用户登录信息
    UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
    
    NSMutableString *priceID = [[NSMutableString alloc] init];//设备价格表ID
    NSMutableString *bszlID = [[NSMutableString alloc] init];//泵送种类ID
    NSMutableString *bsxhID = [[NSMutableString alloc] init];//泵送型号ID
    NSMutableString *tjg = [[NSMutableString alloc] init];//泵送价格
    NSMutableString *bz = [[NSMutableString alloc] init];//备注
    NSMutableString *deleteID = [[NSMutableString alloc] init];//删除ID
    
    //新增修改
    for (int i=0;i<self.resultData.count;i++){
        NSDictionary *dictionary = [self.resultData objectAtIndex:i];
        [priceID appendFormat:@"%@,",[dictionary objectFormatIntegerNumberForKey:@"ID"]];
        [bszlID appendFormat:@"%@,",[dictionary objectFormatIntegerNumberForKey:@"PumpType"]];
        [bsxhID appendFormat:@"%@,",[dictionary objectFormatIntegerNumberForKey:@"PumpNorms"]];
        [tjg appendFormat:@"%@,",[dictionary objectFormatIntegerNumberForKey:@"价格"]];
        [bz appendFormat:@"%@,",[dictionary objectFormatStringForKey:@"备注"]];
        [deleteID appendFormat:@"1,"];
    }
    
    //删除泵送价格（删除=0，不删除=1）
    for (int i=0;i<self.deleteData.count;i++) {
        NSDictionary *dictionary = [self.deleteData objectAtIndex:i];
        [priceID appendFormat:@"%@,",[dictionary objectFormatIntegerNumberForKey:@"ID"]];
        [bszlID appendFormat:@"0,"];
        [bsxhID appendFormat:@"0,"];
        [tjg appendFormat:@"0,"];
        [bz appendFormat:@","];
        [deleteID appendFormat:@"0,"];
    }
    
    //生效时间
    UITextField *textField1 = [self.tableView getCellSaveClass:[UITextField class] pathForRow:0 inSection:0];
    NSString *SXTime = textField1.text;
    
    //提交数据封装
    JGProgressHUD *HUD = [self showSimpleHUDText:@"正在提交中"];
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeGroup];
    [content setModuleType:@"HTGL_BSDJ_AUD"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    
    [content addParameterKey:@"合同ID" value:self.concreteID];
    [content addParameterKey:@"设备价格表ID" value:priceID];
    [content addParameterKey:@"泵送种类ID" value:bszlID];
    [content addParameterKey:@"泵送型号ID" value:bsxhID];
    [content addParameterKey:@"泵送价格" value:tjg];
    [content addParameterKey:@"备注" value:bz];
    [content addParameterKey:@"是否删除" value:deleteID];
    [content addParameterKey:@"用户ID" value:userInfo.Id];
    [content addParameterKey:@"生效时间" value:SXTime];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        [HUD dismissAnimated:YES];//关闭进度框
        
        //添加数据，刷新页面
        NSArray *firstArray = nil;
        if(result.resultArray && result.resultArray.count>0){
            firstArray = [result.resultArray firstObject];
        }
        
        //数据处理及显示
        if(firstArray && firstArray.count>0){
            [self showSuccessHUDText:@"提交成功"];
            if(self.backResultDelagate)[self.backResultDelagate backResultDataKey:@"ModifSuccess" dataValue:nil];
            [self.navigationController popViewControllerAnimated:YES];
            
        } else{
            [self showAlertView:@"提交泵送价格失败，请重新尝试"];
        }
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [HUD dismissAnimated:YES];//关闭进度框
        [self showAlertView:@"系统繁忙，请稍后再试"];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [HUD dismissAnimated:YES];//关闭进度框
        [self showAlertView:@"网络连接异常，请检查网络是否连接"];
    }];
}

#pragma mark - MLPAutoCompleteTextFieldDataSource

- (void)autoCompleteTextField:(MLPAutoCompleteTextField *)textField
 possibleCompletionsForString:(NSString *)string
            completionHandler:(void(^)(NSArray *suggestions))handler
{
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
    dispatch_async(queue, ^{
        
        NSMutableArray *mutableCountries = [NSMutableArray new];
        if(textField == self.pumpClassTextField){
            for(NSDictionary *mDictionary in self.pumpingClassArray){
                NSString *countryName = [mDictionary objectFormatStringForKey:@"Definition"];
                DEMOCustomAutoCompleteObject *country = [[DEMOCustomAutoCompleteObject alloc] initWithCountry:countryName];
                country.object = mDictionary;
                [mutableCountries addObject:country];
            }

        } else if(textField == self.pumpModelTextField){
            for(NSDictionary *mDictionary in self.pumpingModelArray){
                NSString *countryName = [mDictionary objectFormatStringForKey:@"Definition"];
                DEMOCustomAutoCompleteObject *country = [[DEMOCustomAutoCompleteObject alloc] initWithCountry:countryName];
                country.object = mDictionary;
                [mutableCountries addObject:country];
            }
 
        }
        
        NSArray *completions =[NSArray arrayWithArray:mutableCountries];
        handler(completions);
    });
}

#pragma mark - MLPAutoCompleteTextFieldDelegate

- (void)autoCompleteTextField:(MLPAutoCompleteTextField *)textField
  didSelectAutoCompleteString:(NSString *)selectedString
       withAutoCompleteObject:(id<MLPAutoCompletionObject>)selectedObject
            forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(textField == self.pumpClassTextField && selectedObject){
        DEMOCustomAutoCompleteObject *object = selectedObject;
        self.pumpingClassSelectedObject = object.object;
    } else if(textField == self.pumpModelTextField && selectedObject){
        DEMOCustomAutoCompleteObject *object = selectedObject;
        self.pumpingModelSelectedObject = object.object;
    }
}

#pragma mark - UITextFieldDelegate

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    if(textField == self.pumpClassTextField){
        self.pumpingClassSelectedObject = nil;
    } else if(textField == self.pumpModelTextField){
        self.pumpingModelSelectedObject = nil;
    }
    
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if(textField == self.pumpClassTextField && !self.pumpClassTextField){
        textField.text = @"";
    } else if(textField == self.pumpModelTextField && !self.pumpModelTextField){
        textField.text = @"";
    }
}

#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //数据提交
    if (buttonIndex == 0) [self submitNetworkData];
}

#pragma mark - UIAlertView

- (void)showAlertView:(NSString*)message
{
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    alert.alertViewStyle=UIAlertViewStyleDefault;
    [alert show];
}

@end